from datetime import datetime
from typing import Optional, Dict, Any, Tuple
from apps.models.models import Announcements, User
from apps.schemas.schemas import AnnouncementRequest, AnnouncementCreateRequest


async def get_all_announcements(page: int = 1, pagesize: int = 10) -> Tuple[int, list]:
    skip = (page - 1) * pagesize
    limit = pagesize
    total = await Announcements.all().count()
    announcement = await Announcements.all().offset(skip).limit(limit).values(
        'announcement_id', 'title', 'content', 'create_at', 'created_by_id', 'is_active', 'is_pinned')
    return total, list(announcement)


async def update_announcement(data: AnnouncementRequest) -> bool:
    db_announcement = await Announcements.get_or_none(announcement_id=data.announcement_id)
    if db_announcement:
        try:
            await db_announcement.update_from_dict(data.dict())
            await db_announcement.save()
            return True
        except Exception:
            return False
    else:
        return False


async def add_announcement(data: AnnouncementCreateRequest, created_by_id: int = 11) -> bool:
    try:
        await Announcements.create(**data.dict(), created_by_id=created_by_id)
        return True
    except Exception:
        return False


async def delete_announcement(announcement_id: int) -> bool:
    db_announcement = await Announcements.get_or_none(announcement_id=announcement_id)
    if db_announcement:
        try:
            await db_announcement.delete()
            return True
        except Exception:
            return False
    else:
        return False
